package org.rcy.framework.data.service;

import org.rcy.framework.data.dao.CrudMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;


public abstract class AbstractCrudService <T, ID extends Serializable> implements CrudService<T, ID>{

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected CrudMapper<T,ID> mapper;

	/**
	 * 默认构造函数
	 */
	public AbstractCrudService() {
		super();
	}

	@Override
	public T create(T entity) {
		mapper.insertSelective(entity);
		return entity;
	}

	@Override
	public boolean update(T entity) {
		mapper.updateByPrimaryKey(entity);
		return true;
	}

	@Override
	public Optional<T> findById(ID id) {
		T entity = mapper.selectByPrimaryKey(id);
		return Optional.ofNullable(entity);
	}

	@Override
	public T get(ID id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public boolean existsById(ID id) {
		return mapper.existsWithPrimaryKey(id);
	}

	@Override
	public Optional<T> findOne(T entity) {
		T value = mapper.selectOne(entity);
		return Optional.ofNullable(value);
	}

	@Override
	public List<T> query(T entity) {
		return mapper.select(entity);
	}

	@Override
	public boolean delete(ID id) {
		mapper.deleteByPrimaryKey(id);
		return true;
	}

	public void deleteById(ID id) {
		mapper.deleteByPrimaryKey(id);
	}

	@Override
	public void delete(T entity) {
		mapper.delete(entity);
	}

	/**
	 * 失效缓存。需要子类复写。
	 * @param entity
	 */
	protected abstract void evictCache(T entity);

	/**
	 * 是否使用了缓存, 子类可改写。默认不使用。
	 *
	 * @return
	 */
	protected abstract boolean useCache();
}
